'''
Program Assignment:	Assignment 2
Name:			Alberto Massa                                                                      
Date:			11/08/2010                  
Description:            This file contains procedures and classes for handling code file in filesystem. 
'''

'''
Listing Contents:
Compilation instructions
	This module does not contains executable code for direct running.

Includes and dependecies                                                                                                        
	lang.py file (containing lang module) must be in PYTHONPATH or in the same directory

Class and procedures declarations:                                                                                     	
	get_extention: generic procedure for get extention of a file
	CodeFile: class for handle a file containing source code.
	CodeFileWalker: class for walk in filesystem
'''

import os
from os.path import join, getsize

from lang import LanguageFactory

def get_extention(filename):
	'''
	Return extentions of the string that represent a file name.
	'''
	return filename.split('.')[-1]

class CodeFile():
	'''
	Class for handle a source code file.
	Public properties are: name, path, size in byte, language and root.
	language is a Language, see lang.py module.
	root is the root node, Token object, that contains a simple abstract syntax tree. see lang.py

	language and root properties are setted with None.
	'''
	def __init__(self, filename, absolute=False):
		self.name = filename.split('/')[-1]
		self.path = os.path.abspath(filename) 
		self.size_in_byte = getsize(filename)

		self.language = self.root = None

class CodeFileWalker():
	'''
	Class to walk in file system.
	Filter only files of coding language registered in LangueFactory.
	'''
	def __init__(self):
		self.factory = LanguageFactory()

	'''
	Delegate function of LangueFactory.is_known_ext
	'''
	def is_known_file(self, f):
		ext = get_extention(f)
		return self.factory.is_known_ext(ext)

	'''
	Generator function.
	Open directory represented by path string.
	Yields elements of a list of CodeFile objects.
	'''
	def open_directory(self, path):
		#print("CodeFileWalker > open_directory > path: ", path)
		for dirpath, dirnames, filenames in os.walk(path):
			files = [join(dirpath, name) for name in filenames]
			files = filter(self.is_known_file, files)
			for f in files:
				n = CodeFile(f)
				l = self.factory.getlang(get_extention(f))
				#print "CodeFileWalker > open_dir > language: {0}".format(l)
				n.language = l
				yield n

	
